package com.i_art_engineer.meigong.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Environment;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.i_art_engineer.meigong.R;
import com.i_art_engineer.meigong.base.ActionBarActivity;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


public class CameraActivity extends ActionBarActivity {

  static  Bitmap photo = null;
    private View.OnClickListener listener =  new View.OnClickListener(){

        @Override
        public void onClick(View v) {
            MyPictureCallback myPictureCallback   =   new MyPictureCallback();
            switch (v.getId()){

                case R.id.btn_shoot:
                    // 拍照
                    if (camera != null&&IS_TOOK==0) {
                        camera.takePicture(null, null,myPictureCallback);
                    }



                break;
            }

        }
    };

    private LinearLayout ll_title,ll_item_camera,ll_shot;
    private FrameLayout fl_back;
    private TextView tv_title;
    private SurfaceView surfaceView ;
    private Camera camera;
    private Camera.Parameters parameters = null;
    private WindowManager mWindowManager;
    private int windowWidth ;//获取手机屏幕宽度
    private int windowHight ;//获取手机屏幕高度
    private String savePath = "/finger/";
    private Bundle bundle = null;// 声明一个Bundle对象，用来存储数据
    private int IS_TOOK = 0;//是否已经拍照 ,0为否

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        initActionBar(R.string.title_shoot);

        ll_item_camera = (LinearLayout)findViewById(R.id.ll_item_camera);

        ll_shot = (LinearLayout) ll_item_camera.findViewById(R.id.btn_shoot);
        ll_shot.setOnClickListener(listener);

        mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        windowWidth = mWindowManager.getDefaultDisplay().getWidth();
        windowHight = mWindowManager.getDefaultDisplay().getHeight();

        surfaceView = (SurfaceView) this
                .findViewById(R.id.surfaceView);
        surfaceView.getHolder()
                .setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        surfaceView.getHolder().setFixedSize(surfaceView.getWidth(), surfaceView.getHeight()); // 设置Surface分辨率
        surfaceView.getHolder().setKeepScreenOn(true);// 屏幕常亮
        surfaceView.getHolder().addCallback(new SurfaceCallback());// 为S
    }


    // 提供一个静态方法，用于根据手机方向获得相机预览画面旋转的角度
    public static int getPreviewDegree(Activity activity) {
        // 获得手机的方向
        int rotation = activity.getWindowManager().getDefaultDisplay()
                .getRotation();
        int degree = 0;
        // 根据手机的方向计算相机预览画面应该选择的角度
        switch (rotation) {
            case Surface.ROTATION_0:
                degree = 90;
                break;
            case Surface.ROTATION_90:
                degree = 0;
                break;
            case Surface.ROTATION_180:
                degree = 270;
                break;
            case Surface.ROTATION_270:
                degree = 180;
                break;
        }
        return degree;
    }

    /**
     * 重构相机照相回调类
     * @author pc
     *
     */
    private final class SurfaceCallback implements SurfaceHolder.Callback {

        @SuppressWarnings("deprecation")
        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                                   int height) {
            // TODO Auto-generated method stub

            if(camera!=null) {
                parameters = camera.getParameters(); // 获取各项参数
                parameters.setPictureFormat(PixelFormat.JPEG); // 设置图片格式
                parameters.setPreviewSize(width, height); // 设置预览大小
           //     parameters.setPreviewFrameRate(5);  //设置每秒显示4帧
                parameters.setPictureSize(width, height); // 设置保存的图片尺寸
                parameters.setJpegQuality(100); // 设置照片质量
                parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
              camera.setParameters(parameters);
            }else {
                Toast.makeText(CameraActivity.this,"请打开相机的权限后重试！",Toast.LENGTH_SHORT).show();;
                finish();;
            }
        }

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            // TODO Auto-generated method stub
            try {
                camera = Camera.open(); // 打开摄像头
                camera.setPreviewDisplay(holder); // 设置用于显示拍照影像的SurfaceHolder对象

                camera.setDisplayOrientation(getPreviewDegree(CameraActivity.this));

                camera.startPreview(); // 开始预览
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            // TODO Auto-generated method stub
            if (camera != null) {
                camera.release(); // 释放照相机
                camera = null;
            }
        }

    }

    /**
     * 重构照相类
     * @author
     *
     */
    private final class MyPictureCallback implements Camera.PictureCallback {

        @Override
        public void onPictureTaken(byte[] data,final Camera camera) {
            try {
                bundle = new Bundle();
                bundle.putByteArray("bytes", data); //将图片字节数据保存在bundle当中，实现数据交换



                //  camera.startPreview(); // 拍完照后，重新开始预览
                photo = byteToBitmap(data);
                Matrix matrix = new Matrix();
                matrix.setRotate(90);
                photo = Bitmap.createBitmap(photo,0,0,photo.getWidth(),photo.getHeight(),matrix,true);

        showDlg(data);;



            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void  showDlg(final byte[]data){
        final Dialog dlg = new Dialog(CameraActivity.this);
        dlg.requestWindowFeature(Window.FEATURE_NO_TITLE);
        View dlgview = LayoutInflater.from(CameraActivity.this).inflate(R.layout.dlg_takephoto, null);
        dlg.setContentView(dlgview);
        dlg.setCanceledOnTouchOutside(false);
        Button btn_cancel = (Button) dlgview.findViewById(R.id.btn_cancel);
        Button btn_ok = (Button) dlgview.findViewById(R.id.btn_ok);
        dlg.setCanceledOnTouchOutside(false);
        ImageView iv = (ImageView)dlgview.findViewById(R.id.dlg_pic);
        iv.setImageBitmap(photo);
        iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);


        btn_cancel.setClickable(true);
        btn_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dlg.dismiss();
                camera.startPreview();
                IS_TOOK = 0;
            }
        });

        btn_ok.setClickable(true);
        btn_ok.setOnClickListener(new View.OnClickListener() {

            String path = "";
            @Override
            public void onClick(View v) {
                dlg.dismiss();
                Toast.makeText(CameraActivity.this, "点击ok", Toast.LENGTH_SHORT).show();
//                        camera.startPreview();
                IS_TOOK = 1;
                if(isHaveSDCard()) {

                    try {
                        path =  saveToSDCard(data); // 保存图片到sd卡中
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    Toast.makeText(getApplicationContext(), "SDCardsuccess",
                            Toast.LENGTH_SHORT).show();
                }else{
                    try {
                        path =   saveToRoot(data);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    Toast.makeText(getApplicationContext(), "Rootsuccess",
                            Toast.LENGTH_SHORT).show();
                }

                Intent intent = new Intent();
                intent.putExtra("path", path);
                setResult(Activity.RESULT_OK, intent);
                finish();;
            }
        });

        Window dialogWindow = dlg.getWindow();
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        p.height = (int) (d.getHeight() * 0.7); // 高度设置为屏幕的0.6
        p.width = (int) (d.getWidth() * 1.0); // 宽度设置为屏幕的0.65
        dlg.show();
    }

    public static Bitmap getBitmapByPath(String path) throws IOException {
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(
                new File(path)));
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(in, null, options);
        in.close();
        int i = 0;
        Bitmap bitmap = null;
        while (true) {
            if ((options.outWidth >> i <= 1000)
                    && (options.outHeight >> i <= 1000)) {
                in = new BufferedInputStream(
                        new FileInputStream(new File(path)));
                options.inSampleSize = (int) Math.pow(2.0D, i);
                options.inJustDecodeBounds = false;
                bitmap = BitmapFactory.decodeStream(in, null, options);
                break;
            }
            i += 1;
        }
        return bitmap;
    }

    /**
     * 把图片byte流编程bitmap
     * @param data
     * @return
     */
    private Bitmap byteToBitmap(byte[] data){
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap b = BitmapFactory.decodeByteArray(data, 0, data.length,options);
        int i = 0;
        while (true) {
            if ((options.outWidth >> i <= 1000)
                    && (options.outHeight >> i <= 1000)) {
                options.inSampleSize = (int) Math.pow(2.0D, i);
                options.inJustDecodeBounds = false;
                b = BitmapFactory.decodeByteArray(data, 0, data.length, options);
                break;
            }
            i += 1;
        }
        return b;

    }

    /**
     * 检验是否有SD卡
     * @true or false
     */
    public static boolean isHaveSDCard() {
        return Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState());
    }

    public String saveToRoot(byte[] data) throws IOException {
        //剪切为正方形
        Bitmap b = byteToBitmap(data);
        Bitmap bitmap = Bitmap.createBitmap(b, 0, 0, windowWidth, windowWidth );
        //生成文件
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); // 格式化时间
        String filename = format.format(date) + ".jpg";
        File fileFolder = new File(Environment.getRootDirectory()
                + savePath);
        if (!fileFolder.exists()) { // 如果目录不存在，则创建一个名为"finger"的目录
            fileFolder.mkdir();
        }
        File jpgFile = new File(fileFolder, filename);
        FileOutputStream outputStream = new FileOutputStream(jpgFile); // 文件输出流
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
        outputStream.flush();


         //  outputStream.close();
      //    outputStream.write(data); // 写入sd卡中
        outputStream.close(); // 关闭输出流
//        Intent intent = new Intent();
//        intent.putExtra("path",Environment.getExternalStorageDirectory() + savePath + filename);
//        setResult(100, intent);
        String path=Environment.getExternalStorageDirectory() + savePath + filename;

        return path;
    }
    /**
     * 将拍下来的照片存放在SD卡中
     * @param data
     * @throws IOException
     */
    public String saveToSDCard(byte[] data) throws IOException {
        //剪切为正方形
        Bitmap b = byteToBitmap(data);
        Matrix matrix = new Matrix();
        matrix.setRotate(90);
        Bitmap bitmap = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(),matrix,true );
        //生成文件
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); // 格式化时间
        String filename = format.format(date) + ".jpg";
        File fileFolder = new File(Environment.getExternalStorageDirectory()
                + savePath);
        if (!fileFolder.exists()) { // 如果目录不存在，则创建一个名为"finger"的目录
            fileFolder.mkdir();
        }
        File jpgFile = new File(fileFolder, filename);
        FileOutputStream outputStream = new FileOutputStream(jpgFile); // 文件输出流
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
        outputStream.flush();


        //   out.close();
        //  outputStream.write(data); // 写入sd卡中
        outputStream.close(); // 关闭输出流
        String path=Environment.getExternalStorageDirectory() + savePath + filename;
//        Intent intent = new Intent();
//        intent.putExtra("path",Environment.getExternalStorageDirectory() + savePath + filename);
//        setResult(1, intent);
        return path;
    }
}
